<template>
  <div class="serial-number-manage-container">
    <h1 class="page-title">编号管理</h1>
    
    <!-- 搜索和操作区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="编号类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
            <el-option 
              v-for="item in typeOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规则名称">
          <el-input v-model="searchForm.name" placeholder="请输入规则名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="规则代码">
          <el-input v-model="searchForm.code" placeholder="请输入规则代码" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleSearchReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd">新增规则</el-button>
        <el-button type="success" @click="handleImport">导入规则</el-button>
        <el-button type="warning" @click="handleExport">导出规则</el-button>
        <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
          批量删除
        </el-button>
      </div>
    </el-card>
    
    <!-- 编号规则列表 -->
    <el-card class="table-card">
      <el-table 
        :data="tableData" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
        border
        style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="type" label="规则代码" width="120">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.bizType)">
              {{ getTypeLabel(scope.row.bizType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="prefix" label="前缀" width="100"></el-table-column>
        <el-table-column prop="dateFormat" label="日期格式" width="120"></el-table-column>
        <el-table-column prop="seqLength" label="补零长度" width="120"></el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" size="small" @click="handlePreview(scope.row)">预览</el-button>
            <el-button type="warning" size="small" @click="handleReset(scope.row)">重置</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 新增/编辑编号规则对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="700px"
      @close="handleDialogClose">
      <el-form :model="serialNumberForm" :rules="serialNumberRules" ref="serialNumberFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规则类型" prop="bizType">
              <el-input v-model="serialNumberForm.bizType" placeholder="请输入规则类型编码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="前缀" prop="prefix">
              <el-input v-model="serialNumberForm.prefix" placeholder="请输入规则代码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="日期格式" prop="dateFormat">
              <el-select v-model="serialNumberForm.dateFormat" placeholder="请选择日期格式" style="width: 100%">
                <el-option label="YYYY-MM-DD" value="YYYY-MM-DD"></el-option>
                <el-option label="YYYYMMDD" value="YYYYMMDD"></el-option>
                <el-option label="YYYY-MM" value="YYYY-MM"></el-option>
                <el-option label="YYYYMM" value="YYYYMM"></el-option>
                <el-option label="无" value=""></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 预览编号对话框 -->
    <el-dialog v-model="previewDialogVisible" title="编号预览" width="500px">
      <div class="preview-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="规则名称">{{ previewData.name }}</el-descriptions-item>
          <el-descriptions-item label="规则代码">{{ previewData.code }}</el-descriptions-item>
          <el-descriptions-item label="当前编号">{{ previewData.currentNumber }}</el-descriptions-item>
          <el-descriptions-item label="下一个编号">{{ previewData.nextNumber }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="preview-examples" v-if="previewData.examples && previewData.examples.length">
          <h4>示例编号</h4>
          <el-tag v-for="(example, index) in previewData.examples" :key="index" style="margin: 5px;">
            {{ example }}
          </el-tag>
        </div>
      </div>
      <template #footer>
        <el-button @click="previewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    
    <!-- 导入编号规则对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入编号规则" width="500px">
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :limit="1"
        accept=".json,.xlsx,.xls"
        :on-change="handleFileChange"
        :file-list="fileList">
        <el-button type="primary">选择文件</el-button>
        <template #tip>
          <div class="el-upload__tip">
            支持JSON、Excel格式文件，文件大小不超过10MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleImportSubmit" :loading="importLoading">导入</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getSerialNumberList,
  createSerialNumber,
  updateSerialNumber,
  deleteSerialNumber,
  batchDeleteSerialNumber,
  getSerialNumberTypes,
  exportSerialNumber,
  importSerialNumber,
  resetSerialNumber,
  previewSerialNumber
} from '@/api/serialNumber'

// 搜索表单
const searchForm = reactive({
  type: '',
  name: '',
  code: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const serialNumberFormRef = ref(null)
const serialNumberForm = reactive({
  id: null,
  bizType: '',
  prefix: '',
  dateFormat: ''
})

// 表单验证规则
const serialNumberRules = {
}

// 类型选项
const typeOptions = ref([])

// 预览相关
const previewDialogVisible = ref(false)
const previewData = ref({})
const previewNumber = ref('')

// 导入相关
const importDialogVisible = ref(false)
const uploadRef = ref(null)
const fileList = ref([])
const importLoading = ref(false)

// 获取类型标签
const getTypeLabel = (value) => {
  const option = typeOptions.value.find(item => item.value === value)
  return option ? option.label : value
}

// 获取类型标签类型
const getTypeTagType = (value) => {
  const typeMap = {
    'student': 'primary',
    'teacher': 'success',
    'course': 'warning',
    'class': 'danger',
    'grade': 'info',
    'exam': 'primary',
    'certificate': 'success'
  }
  return typeMap[value] || ''
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 获取编号规则列表
const fetchSerialNumberList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...searchForm
    }
    
    const response = await getSerialNumberList(params)
    console.log('API响应:', response)
    
    // 安全处理数据
    let dataArray = []
    let totalCount = 0
    
    if (response && response.data) {
      // 分页结构：{ records: [], total: 100 }
      if (response.data.records && Array.isArray(response.data.records)) {
        dataArray = response.data.records
        totalCount = response.data.total || 0
      } 
      // 直接数组结构
      else if (Array.isArray(response.data)) {
        dataArray = response.data
        totalCount = response.data.length
      }
      // 其他可能的结构
      else if (response.data.list && Array.isArray(response.data.list)) {
        dataArray = response.data.list
        totalCount = response.data.total || response.data.list.length
      }
    }
    
    tableData.value = dataArray
    pagination.total = totalCount
    
    console.log('处理后的数据:', tableData.value)
    console.log('总数:', pagination.total)
    
  } catch (error) {
    console.error('获取编号规则列表失败:', error)
    ElMessage.error('获取编号规则列表失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 获取编号类型
const fetchSerialNumberTypes = async () => {
  try {
    const response = await getSerialNumberTypes()
    typeOptions.value = response.data || []
  } catch (error) {
    console.error('获取编号类型失败:', error)
    // 使用默认类型
    typeOptions.value = [
      { value: 'student', label: '学生编号' },
      { value: 'teacher', label: '教师编号' },
      { value: 'course', label: '课程编号' },
      { value: 'class', label: '班级编号' },
      { value: 'grade', label: '成绩编号' },
      { value: 'exam', label: '考试编号' },
      { value: 'certificate', label: '证书编号' }
    ]
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchSerialNumberList()
}

// 重置搜索
const handleSearchReset = () => {
  Object.assign(searchForm, {
    type: '',
    name: '',
    code: ''
  })
  pagination.currentPage = 1
  fetchSerialNumberList()
}

// 新增编号规则
const handleAdd = () => {
  dialogTitle.value = '新增编号规则'
  dialogVisible.value = true
  Object.assign(serialNumberForm, {
    id: null,
    bizType: '',
    prefix: '',
    dateFormat: ''
  })
  previewNumber.value = ''
}

// 编辑编号规则
const handleEdit = (row) => {
  dialogTitle.value = '编辑编号规则'
  dialogVisible.value = true
  Object.assign(serialNumberForm, {
    id: row.id,
    type: row.type,
    name: row.name,
    code: row.code,
    prefix: row.prefix,
    dateFormat: row.dateFormat,
    separator: row.separator,
    startValue: row.startValue,
    currentValue: row.currentValue,
    step: row.step,
    digitCount: row.digitCount,
    isCircular: row.isCircular,
    maxValue: row.maxValue,
    description: row.description
  })
  updatePreview()
}

// 预览编号规则
const handlePreview = async (row) => {
  try {
    const response = await previewSerialNumber({
      ...row,
      count: 5 // 预览5个示例
    })
    previewData.value = response.data || {}
    previewDialogVisible.value = true
  } catch (error) {
    console.error('预览编号规则失败:', error)
    ElMessage.error('预览编号规则失败')
  }
}

// 重置编号规则
const handleReset = (row) => {
  ElMessageBox.confirm(`确定要重置编号规则"${row.name}"吗？当前值将重置为起始值。`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await resetSerialNumber(row.id)
      ElMessage.success('重置成功')
      fetchSerialNumberList()
    } catch (error) {
      console.error('重置编号规则失败:', error)
      ElMessage.error('重置编号规则失败')
    }
  }).catch(() => {
    // 用户取消重置
  })
}

// 删除编号规则
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除编号规则"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteSerialNumber(row.id)
      ElMessage.success('删除成功')
      fetchSerialNumberList()
    } catch (error) {
      console.error('删除编号规则失败:', error)
      ElMessage.error('删除编号规则失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 批量删除
const handleBatchDelete = () => {
  const ids = selectedRows.value.map(row => row.id)
  ElMessageBox.confirm(`确定要删除选中的${ids.length}个编号规则吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await batchDeleteSerialNumber(ids)
      ElMessage.success('批量删除成功')
      fetchSerialNumberList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchSerialNumberList()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchSerialNumberList()
}

// 更新预览
const updatePreview = () => {
  if (!serialNumberForm.prefix && !serialNumberForm.dateFormat && !serialNumberForm.separator) {
    previewNumber.value = '请填写规则信息'
    return
  }
  
  let preview = serialNumberForm.prefix || ''
  
  // 添加日期部分
  if (serialNumberForm.dateFormat) {
    if (preview && serialNumberForm.separator) {
      preview += serialNumberForm.separator
    }
    const today = new Date()
    if (serialNumberForm.dateFormat === 'YYYY-MM-DD') {
      preview += today.getFullYear() + '-' + 
                 String(today.getMonth() + 1).padStart(2, '0') + '-' + 
                 String(today.getDate()).padStart(2, '0')
    } else if (serialNumberForm.dateFormat === 'YYYYMMDD') {
      preview += today.getFullYear() + 
                 String(today.getMonth() + 1).padStart(2, '0') + 
                 String(today.getDate()).padStart(2, '0')
    } else if (serialNumberForm.dateFormat === 'YYYY-MM') {
      preview += today.getFullYear() + '-' + 
                 String(today.getMonth() + 1).padStart(2, '0')
    } else if (serialNumberForm.dateFormat === 'YYYYMM') {
      preview += today.getFullYear() + 
                 String(today.getMonth() + 1).padStart(2, '0')
    }
  }
}

// 监听表单变化，更新预览
watch([
  () => serialNumberForm.prefix,
  () => serialNumberForm.dateFormat,
  () => serialNumberForm.separator,
  () => serialNumberForm.currentValue,
  () => serialNumberForm.step,
  () => serialNumberForm.digitCount
], () => {
  if (dialogVisible.value) {
    updatePreview()
  }
}, { deep: true })

// 提交表单
const handleSubmit = async () => {
  try {
    // 1. 验证表单
    await serialNumberFormRef.value.validate()
    console.log('表单验证通过，准备提交数据:', serialNumberForm)
    
    if (serialNumberForm.id) {
      // 更新操作
      console.log('执行更新操作，ID:', serialNumberForm.id)
      const result = await updateSerialNumber(serialNumberForm.id, serialNumberForm)
      console.log('更新操作结果:', result)
      ElMessage.success('更新成功')
    } else {
      // 新增操作
      console.log('执行新增操作，数据:', JSON.stringify(serialNumberForm, null, 2))
      const result = await createSerialNumber(serialNumberForm)
      console.log('新增操作结果:', result)
      ElMessage.success('新增成功')
    }
    
    dialogVisible.value = false
    await fetchSerialNumberList() // 等待列表刷新完成
    console.log('操作完成，对话框已关闭，列表已刷新')
    
  } catch (error) {
    console.error('提交失败 - 完整错误信息:', error)
    
    // 详细错误分类处理
    if (error.response) {
      // 服务器返回了错误状态码
      console.error('服务器错误响应:', error.response)
      const errorMsg = error.response.data?.message || error.response.data?.msg || error.response.statusText
      ElMessage.error(`服务器错误: ${error.response.status} - ${errorMsg}`)
    } else if (error.request) {
      // 请求发送了但没有收到响应
      console.error('网络错误，未收到响应:', error.request)
      ElMessage.error('网络错误，请检查服务器连接')
    } else if (error.message && error.message.includes('validate')) {
      // 表单验证错误
      console.error('表单验证错误:', error.message)
      ElMessage.error('请检查表单填写是否正确')
    } else {
      // 其他错误
      console.error('其他错误:', error.message)
      ElMessage.error(`提交失败: ${error.message || '未知错误'}`)
    }
  }
}

// 对话框关闭
const handleDialogClose = () => {
  serialNumberFormRef.value?.resetFields()
  previewNumber.value = ''
}

// 导入编号规则
const handleImport = () => {
  importDialogVisible.value = true
  fileList.value = []
}

// 文件变化
const handleFileChange = (file, fileList) => {
  // 这里可以添加文件类型和大小验证
}

// 提交导入
const handleImportSubmit = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请选择要导入的文件')
    return
  }
  
  importLoading.value = true
  try {
    const formData = new FormData()
    formData.append('file', fileList.value[0].raw)
    
    await importSerialNumber(formData)
    ElMessage.success('导入成功')
    importDialogVisible.value = false
    fetchSerialNumberList()
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败')
  } finally {
    importLoading.value = false
  }
}

// 导出编号规则
const handleExport = async () => {
  try {
    const params = { ...searchForm }
    const response = await exportSerialNumber(params)
    
    // 创建下载链接
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `serial-number-rules_${new Date().getTime()}.json`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 初始化
onMounted(() => {
  fetchSerialNumberTypes()
  fetchSerialNumberList()
})
</script>

<style scoped>
.serial-number-manage-container {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
}

.search-card {
  margin-bottom: 20px;
}

.operation-buttons {
  margin-top: 15px;
  display: flex;
  gap: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.preview-content {
  margin-bottom: 20px;
}

.preview-examples {
  margin-top: 20px;
}

.preview-examples h4 {
  margin-bottom: 10px;
  color: #606266;
}
</style>